<?php
namespace common\services;

use common\helpers\TStringHelper;
use common\models\User;
use common\models\UserCompany;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;

class UserCompanyServices extends UserCompany
{

    public function search($params = array()) {
        $model = UserCompany::find(false);
        $model->orderBy('id desc');

        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['type']) && $params['type'] != '') {
            $model->andFilterWhere(['=', 'type', $params['type']]);
        }
        if (isset($params['status']) && $params['status'] != '') {
            $model->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or', ['like', 'name', $params['keywords']], ['telphone', 'introduce', $params['keywords']]]);
        }

        //$sql = $model->createCommand()->getRawSql();

        return $dataProvider;
    }

    /**
     * 获取用户公司信息
     * @param $userId
     * @param $type
     * @return UserCompany|mixed|null|static
     */
    public function getUserCompanyInfo($userId, $type){
        $model = UserCompany::findOne(['user_id' => $userId, 'type' => $type]);
        if (empty($model)) {
            $model = new UserCompany();
            $model->user_id = $userId;
            $model->type = $type;
            $model->save();
        }
        return $model;
    }

}
